<template>
  <div>
    <!-- 退单管理 -->
    <el-table-form :inline="true" :model="query" class="demo-form">
      <el-form-item class="merge-item">
        <el-select v-model="csmType" style="width: 160px; margin-right: 2px;">
          <el-option label="订单编号" value="orderCode" />
          <el-option label="申请人" value="createUser" />
          <el-option label="备注" value="remark" />
        </el-select>
        <el-input v-model="csmText" placeholder="请输入内容" clearable />
      </el-form-item>
      <el-form-item label="申请机构" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="状态" prop="refundStatus">
        <el-select v-model="query.refundStatus" placeholder="请选择">
          <el-option
            v-for="item in refundStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核机构" prop="auditOrgSNNo">
        <el-tree-select
          v-model="query.auditOrgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="申请日期" value="createTime" />
          <el-option label="审核日期" value="auditDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="订单来源">
        <el-select v-model="query.orderSource" placeholder="请选择">
          <el-option
            v-for="item in orderSourceMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核人">
        <el-select v-model="query.auditorId" :loading="$loadingPlugin.getOwnerList" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in ownerList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <!-- 查询按钮 -->
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <!-- 导出按钮 -->
    <div class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-folder-opened" style="margin-bottom: 20px;">导出</el-button>
      </div>
    </div>
    <!-- 表单 -->
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      :total="tableData.total"
      pagination
      custom-column
      @fetch="fetchData"
    />
    <audio id="newOrderRefundAudio"><source :src="require('@/assets/sound/new_order_refund.mp3')" type="audio/mpeg"> </audio>
    <backOrderDetails ref="backOrderDetails" />
    <orderDetails ref="orderDetails" />
    <backConfirm ref="backConfirm" />
    <reallocate ref="reallocate" :tree-data="treeData" />
    <flow-info ref="flowInfo" />
  </div>
</template>

<script>
  import { queryMap, queryRefundOrderList, queryOwnerList } from '@/api'
  import BackOrderDetails from './components/BackOrderDetails'
  import OrderDetails from '../../components/OrderDetails'
  import BackConfirm from './components/BackConfirm'
  import Reallocate from './components/Reallocate'
  import FlowInfo from '../../components/OrderFlowInfoModal'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import moment from 'dayjs'

  const colorObj = {
    '1': 'color:#EA8511;',
    '2': 'color:#0066ff;',
    '3': 'color:#ff0000;'
  }

  export default {
    name: 'backOrderManage',
    components: {
      BackOrderDetails,
      OrderDetails,
      BackConfirm,
      Reallocate,
      FlowInfo
    },
    data() {
      return {
        actionColWidth: 80,
        currentOrg: null,
        treeData: [],
        ownerList: [],
        csmType: 'orderCode',
        csmText: '',
        dateType: 'createTime',
        date: [moment().startOf('day'), moment().endOf('day')],
        query: {
          orgSNNo: '',
          auditOrgSNNo: '',
          refundStatus: 1, // 默认选中待处理
          auditorId: '',
          fromPlat: ''
        },
        orderSourceMap: [],
        refundStatusMap: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ]),
      column: function() {
        return [
          {
            prop: 'orderCode',
            label: '订单号',
            width: 110,
            render: (h, { row }) => <el-link onClick={() => this.openOrderDetails(row)}>{row.orderCode}</el-link>
          },
          {
            prop: 'ownerName',
            label: '申请人',
            width: 130,
            render: (h, { row }) => {
              if (row.ownerType === 1) {
                return <span>{row.ownerName}(<span class='red-text'>内部员工</span>)</span>
              } else if (row.ownerType === 2) {
                return <span>{row.ownerName}(<span class='red-text'>客户</span>)</span>
              }
            }
          },
          {
            prop: 'createTime',
            label: '申请时间',
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'refundStatus',
            label: '状态',
            render: (h, { row }) => <span style={colorObj[row.refundStatus]}>{ row.refundStatus && formatColumnMap(this.refundStatusMap, 'value', row.refundStatus, 'desc') }</span>
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            prop: 'auditOrgName',
            label: '审核机构',
            width: 110
          },
          {
            prop: 'auditor',
            label: '审核人'
          },
          {
            prop: 'auditDt',
            label: '审核时间',
            render: (h, { row }) => <span>{ row.auditDt && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'fromPlat',
            label: '订单来源',
            render: (h, { row }) => <span>{ row.fromPlat && formatColumnMap(this.orderSourceMap, 'value', row.fromPlat, 'desc') }</span>
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'contactPhone',
            label: '联系电话',
            width: 110
          },
          {
            prop: 'csmAddress',
            label: '地址',
            width: 110
          },
          {
            prop: 'orgName',
            label: '申请机构',
            width: 110
          },
          {
            prop: 'transactor',
            label: '下单人'
          },
          {
            prop: 'transactTime',
            label: '下单时间',
            width: 110,
            render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.refundStatus === 1 && <el-link size='mini' onClick={() => this.openBackConfirm(row, $index)}>
                    退单确认
                  </el-link>}
                  {row.refundStatus === 1 && <el-link size='mini' onClick={() => this.openReallocate(row, $index)}>
                    重新分派
                  </el-link>}
                  <el-link size='mini' onClick={() => this.openFlow(row, $index)}>
                    流转信息
                  </el-link>
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.queryOptionsMap()])
    },
    mounted() {
      const _this = this
      this.timer = setInterval(function() {
        _this.fetchData()
      }, 60000)
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.csmType] = this.csmText
        if (this.date && this.date.length === 2) {
          query[this.dateType] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
        }
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 93) {
          this.$message.warning('退单处理申请时间最大支持查询3个月')
          return
        }
        const res = await queryRefundOrderList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
        this.queryNew()
      },
      // 查询是否有新的退单，如果有，则播放语音
      async queryNew() {
        const paramInfo = {
          refundStatus: 1,
          createTime: moment(new Date()).format(),
          currentPage: 1,
          pageSize: 1
        }
        const res = await queryRefundOrderList(paramInfo)
        if (res.data.total > 0) {
          const dom = document.getElementById('newOrderRefundAudio')
          dom.play()
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 获取处理人列表
      async getOwnerList() {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const orgId = this.currentOrg ? this.currentOrg.orgId : -1
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownerList = res.data
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.getOwnerList()
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2] = await Promise.all([mergeAsyncFunc(queryMap, { enumName: 'RefundStatus' }), mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })])
        this.refundStatusMap = res1.data // 订单状态
        this.orderSourceMap = res2.data // 订单来源
      },
      async openOrderDetails(row) {
        await this.$refs.orderDetails.open(row)
      },
      // 退单
      async openBackConfirm(row) {
        await this.$refs.backConfirm.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async openReallocate(row) {
        await this.$refs.reallocate.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击流转信息
      async openFlow(row) {
        await this.$refs.flowInfo.open(row.orderCode)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .btn-group {
    display: flex;
    justify-content: space-between;
  }
  .red-text {
    color: $dangerColor;
  }
</style>
